package io.codescience.aianaly.service;

import io.codescience.aianaly.model.User;
import io.codescience.aianaly.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

@Service
public class AdminSetupService {

    @Autowired
    private UserRepository userRepository;


    @EventListener(ApplicationReadyEvent.class)
    public void initAdminUser() {
        // 检查是否已存在管理员
        if (userRepository.findByRole(User.Role.ADMIN).isEmpty()) {
            User adminUser = new User();
            adminUser.setEmail("admin@yyy.com");
            adminUser.setPassword("admin123"); // 生产环境应该使用加密密码
            adminUser.setUsername("系统管理员");
            adminUser.setRole(User.Role.ADMIN);
            adminUser.setAvatarUrl("/static/images/img_02.png");

            userRepository.save(adminUser);
            System.out.println("默认管理员账户已创建: admin@yyy.com / admin123");
        }
    }

    /**
     * 将现有用户提升为管理员
     */
    public boolean promoteToAdmin(String email) {
        User user = userRepository.findByEmail(email).orElse(null);
        if (user != null) {
            user.setRole(User.Role.ADMIN);
            userRepository.save(user);
            return true;
        }
        return false;
    }

    /**
     * 将用户降级为普通用户
     */
    public boolean demoteToUser(String email) {
        User user = userRepository.findByEmail(email).orElse(null);
        if (user != null) {
            user.setRole(User.Role.USER);
            userRepository.save(user);
            return true;
        }
        return false;
    }
}